package gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.StringReader;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;

import parsing.CritterParser;
import parsing.InvalidSyntaxException;
import parsing.productions.Program;

import world.Critter;

public class GenomeFrame extends JFrame {

	private Critter crit;
	private CritterParser parser;

	private JPanel containerPanel;
	private JTextArea genomeText;
	private JPanel buttonPanel;
	private JButton saveButton;
	private JButton cancelButton;

	private final Color bkg = new Color(255,99,71);
	
	public GenomeFrame(Critter c){
		crit = c;
		parser = new CritterParser();
		
		setSize(400, 500);
		setTitle("Edit selected critter's genome");
		containerPanel = new JPanel();
		containerPanel.setLayout(new BoxLayout(containerPanel, BoxLayout.Y_AXIS));
		containerPanel.setBorder(new LineBorder(bkg, 3));
		add(containerPanel);
		
		Program genome = crit.getGenome();
		StringBuffer sb = new StringBuffer();
		if(genome != null)
			genome.prettyPrint(sb);
		genomeText = new JTextArea(sb.toString()){
			public Dimension getMinimumSize(){
				return new Dimension(0, 400);
			}
		};
		containerPanel.add(new JScrollPane(genomeText));
		
		buttonPanel = new JPanel(){
			public Dimension getMaximumSize(){
				return new Dimension(1000, 30);
			}
		};
		containerPanel.add(buttonPanel);
		saveButton = new JButton("Save");
		saveButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				boolean finished = false;
				try {
					String newProgram = genomeText.getText();
					Program newGenome;
					if(newProgram.equals(""))
						newGenome = null;
					else
						newGenome = parser.parse(new StringReader(newProgram));
					crit.setGenome(newGenome);
					SwingUtilities.getWindowAncestor(saveButton).dispose();
					finished = true;
				} catch (InvalidSyntaxException e1) {
					JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(saveButton),
									"The syntax of the given program is invalid.", "Error", JOptionPane.ERROR_MESSAGE);
				}
			}
		});
		cancelButton = new CancelButton();
		
		buttonPanel.add(saveButton);
		buttonPanel.add(Box.createHorizontalStrut(20));
		buttonPanel.add(cancelButton);

		containerPanel.setBackground(bkg);
		buttonPanel.setBackground(bkg);
		setVisible(true);
	}
}
